import {createRouter, createWebHashHistory} from 'vue-router'
import {dynamicRoutes, routes} from "@/router/routes";
import {createRouteGuard} from "@/router/guard";

/**
 *  @zh_CN 创建vue-router实例
 */
const router = createRouter({
    history: createWebHashHistory(import.meta.env.BASE_URL),
    routes
})

// 动态添加路由
export const dynamicAddRoutes = (menus: []) => {
    // 是否有新路由
    let hasNewRoutes = false;

    const seekRoutesByMenuList = (menuList: []) => {
        menuList.forEach((e) => {
            const item = dynamicRoutes.find(o => o.path === e.path)
            if(item && !router.hasRoute(item.path)) {

                router.addRoute("Layout", item)

                hasNewRoutes = true;
            }
            if (e.children && e.children.length > 0) {
                seekRoutesByMenuList(e.children)
            }
        })
    }
    seekRoutesByMenuList(menus)

    return hasNewRoutes;
}

// 创建路由守卫
createRouteGuard(router)

export default router;
